<template>
  <div
    v-if="visible"
    style="position: absolute; top: 0; right: 0; bottom: 0; left: 0"
  >
    <div style="height: 28px">
      <el-button-group>
        <el-button :icon="DocumentAdd" type="primary" @click="toShowReport">
          报工
        </el-button>

        <el-button
          :disabled="!state.currentRow || state.currentRow.rkLm"
          :icon="HomeFilled"
          type="success"
          @click="toInStore"
        >
          入库
        </el-button>
        <el-button
          :disabled="
            !state.currentRow ||
            !state.currentRow.rkLm ||
            state.currentRow.inspectQty > 0
          "
          :icon="HomeFilled"
          type="warning"
          @click="inspect"
        >
          报检
        </el-button>
        <el-button
          :disabled="!state.currentRow || !state.currentRow.rkLm"
          :icon="Printer"
          type="primary"
          @click="toPrint"
        >
          打印
        </el-button>
      </el-button-group>
      <el-select
        v-model="state.printTemplateCode"
        placeholder="请选择打印模板"
        style="margin-left: 12px"
      >
        <el-option
          v-for="item in state.mbList"
          :key="item.printTemplateCode"
          :label="item.printTemplateName"
          :value="item.printTemplateCode"
        />
      </el-select>
    </div>
    <el-table
      :data="state.reportList"
      highlight-current-row
      style="
        width: 100%;
        height: calc(100vh - 140px);
        margin-top: 12px;
        border-radius: 5px;
      "
      @current-change="handleCurrentChange"
    >
      <el-table-column label="报工编号" prop="reportCode" width="125px" />

      <el-table-column label="班次" width="120px">
        <template #default="{ row }">
          <div>
            <div style="font-size: 14px; color: #666">
              {{ row.banciDate }}
            </div>
            <div style="font-size: 16px; font-weight: 700; color: #333">
              {{ row.banciName }}
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="物料" min-width="200px">
        <template #default="{ row }">
          <div>
            <div style="font-size: 14px; color: #666">
              {{ row.invcode }}
            </div>
            <div style="font-size: 16px; font-weight: 700; color: #333">
              {{ row.invname }}
            </div>
            <div style="font-size: 14px; color: #666">
              {{ row.invspec }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="物料批次" prop="invbatch" width="130px" />
      <el-table-column label="报工数量" prop="reportQty" width="100" />
      <el-table-column label="合格数量" prop="qualifiedQty" width="100">
        <template #default="{ row }">
          <span style="font-size: 16px; font-weight: 700; color: #13ce66">
            {{ row.qualifiedQty }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="返工" prop="fangongQty" width="100">
        <template #default="{ row }">
          <span style="font-size: 16px; font-weight: 700; color: #e62b46">
            {{ row.fangongQty }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="报废数量" prop="scrapQty" width="100">
        <template #default="{ row }">
          <span style="font-size: 16px; font-weight: 700; color: #e62b46">
            {{ row.scrapQty }}
          </span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="报检" prop="blLm" width="80">
        <template #default="{ row }">
          <el-icon
            v-if="row.blLm"
            style="font-size: 24px; font-weight: bold; color: #13ce66"
          >
            <Check />
          </el-icon>
          <el-icon
            v-else
            style="font-size: 24px; font-weight: bold; color: #e62b46"
          >
            <Minus />
          </el-icon>
        </template>
      </el-table-column> -->
      <el-table-column label="入库" prop="rkLm" width="80">
        <template #default="{ row }">
          <el-icon
            v-if="row.rkLm"
            style="font-size: 24px; font-weight: bold; color: #13ce66"
          >
            <Check />
          </el-icon>
          <el-icon
            v-else
            style="font-size: 24px; font-weight: bold; color: #e62b46"
          >
            <Minus />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column label="报检" width="100">
        <template #default="scope">
          <el-icon v-if="scope.row.inspectQty > 0" color="#30DF80" size="20">
            <Select />
          </el-icon>
          <el-icon v-else color="#DF3730" size="20">
            <SemiSelect />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="合格数"
        prop="checkQualifiedQty"
        width="110"
      >
        <template #default="scope">
          <p style="margin: 0px; font-weight: 600; color: #9932cc">
            {{ scope.row.checkQualifiedQty }} {{ scope.row.measName }}
          </p>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="不合格数"
        prop="checkUnqualifiedQty"
        width="110"
      >
        <template #default="scope">
          <p style="margin: 0px; font-weight: 600; color: #9932cc">
            {{ scope.row.checkUnqualifiedQty }} {{ scope.row.measName }}
          </p>
        </template>
      </el-table-column>
      <el-table-column label="报工信息" width="160px">
        <template #default="{ row }">
          <div>
            <div>{{ row.reUserName }}</div>
            <div>{{ row.reTime }}</div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="reportVisible" class="report-module">
      <el-form :data="state.form">
        <el-form-item label="合格">
          <el-input-number
            v-model="state.form.qualifiedQty"
            :controls="false"
            placeholder="请录入合格数"
            style="width: 100%"
            @blur="() => toChangeQty('qualifiedQty')"
          />
        </el-form-item>
        <!-- <el-form-item label="报检">
          <el-input-number
            v-model="state.form.declareQty"
            :controls="false"
            placeholder="请录入报检数"
            style="width: 100%"
            @blur="() => toChangeQty('declareQty')"
          />
        </el-form-item> -->
        <el-form-item label="返工">
          <el-input-number
            v-model="state.form.fangongQty"
            :controls="false"
            placeholder="请录入返工数"
            style="width: 100%"
            @blur="() => toChangeQty('fangongQty')"
          />
        </el-form-item>
        <el-form-item label="报废">
          <el-input-number
            v-model="state.form.scrapQty"
            :controls="false"
            placeholder="请录入报废数"
            style="width: 100%"
            @blur="() => toChangeQty('scrapQty')"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="state.form.remark"
            placeholder="请录入备注"
            style="width: 100%"
            @blur="() => toChangeQty('remark')"
          />
        </el-form-item>
      </el-form>
      <div class="report-mold-root scrollable">
        <div
          v-for="(reportItem, reportIndex) in state.reportDataList"
          :key="reportItem.pkDispatch"
          class="report-mold-item"
          @click="toChangeAlone(reportItem, reportIndex)"
        >
          <div class="report-invname">{{ reportItem.invname }}</div>
          <div class="report-invcode">{{ reportItem.invcode }}</div>
          <div class="report-data-root">
            <div style="flex: 1">
              <div class="report-label">合格数</div>
              <div class="report-val" style="color: #1890ff">
                {{ reportItem.mesReport.qualifiedQty }}
              </div>
            </div>
            <div style="flex: 1">
              <div class="report-label">报检数</div>
              <div class="report-val" style="color: rgb(19, 206, 102)">
                {{ reportItem.mesReport.declareQty }}
              </div>
            </div>
            <div style="flex: 1">
              <div class="report-label">报废数</div>
              <div class="report-val" style="color: #e6a23c">
                {{ reportItem.mesReport.scrapQty }}
              </div>
            </div>
          </div>
          <div class="report-invcode">{{ reportItem.mesReport.remark }}</div>
        </div>
      </div>

      <div v-if="state.dispatchData.useMold" class="btn-root">
        <div
          :class="[state.pickBox ? 'btn-package' : 'btn-disable']"
          style="flex: 1"
          @click="toPackageReport"
        >
          <vab-icon icon="first-aid-kit-line" />
          {{
            state.pickBox
              ? `每${state.pickBox.measName}${state.pickBox.rate}`
              : '无包装方式'
          }}
        </div>
        <div class="btn-report" style="flex: 1" @click="toReport">报工</div>
      </div>
      <div v-else class="btn-root">
        <div class="btn-report" style="flex: 1" @click="toReport">报工</div>
      </div>
      <el-icon
        style="
          position: absolute;
          top: 12px;
          right: 12px;
          z-index: 999;
          font-size: 24px;
          color: #333;
        "
        @click="toCloseReportFrom"
      >
        <Close />
      </el-icon>
    </div>
    <changeQtyDialog
      ref="changeQtyDialogRef"
      @change-callback="changeCallback"
    />
    <inspectDialog
      ref="inspectDialogRef"
      @success-callback="insepectCallback"
    />
  </div>
</template>
<script setup>
  import { webPrintBarcodeApi } from '@/api/kc/barcode_record.ts'
  import { queryTemp } from '@/api/print/index.js'
  import changeQtyDialog from '../dialog/changeQtyDialog.vue'
  import {
    Check,
    Minus,
    Close,
    DocumentAdd,
    HomeFilled,
    Printer,
    Select,
    SemiSelect,
  } from '@element-plus/icons-vue'
  import {
    getReportByPkMidApi,
    queryPickingBoxApi,
    mesReportMoldApi,
    mesReportAloneApi,
    getReportBillApi,
  } from '@/api/mes/report_api.ts'
  import {
    getPickingForMoldApi,
    getMaterialHMoldApi,
    getMaterialHApi,
    getMesPickingApi,
  } from '@/api/mes/material_api.ts'
  import { addWmsProductApi } from '@/api/wms/wms_product.ts'
  import { localStorageConfig } from '@/config/localstorage.config'
  import inspectDialog from '../dialog/inspectDialog.vue'

  import hiPrint from '@/utils/hiPrint.js'
  const pkCorp = localStorage.getItem(localStorageConfig.__pkCorp)
  const $baseMessage = inject('$baseMessage'),
    $baseLoading = inject('$baseLoading')
  const changeQtyDialogRef = ref()
  const visible = ref(false),
    reportVisible = ref(false)
  const state = reactive({
    printTemplateCode: '',
    equipData: null,
    dispatchData: null,
    reportList: [],
    form: {},
    pickBox: null,
    reportDataList: [],
    pickingForList: [], // 应领
    materialList: [], // 已领
    currentRow: null,
    mbList: [],
  })
  const inspectDialogRef = ref()

  const handleCurrentChange = (val) => {
    state.currentRow = val
  }

  const toReport = () => {
    if (state.dispatchData.useMold) {
      doMoldReport()
    } else {
      doMesReport()
    }
  }
  const toCloseReportFrom = () => {
    reportVisible.value = false
  }

  const toInStore = async () => {
    if (state.currentRow) {
      const load = $baseLoading()
      try {
        const res = await addWmsProductApi(state.currentRow)
        load.close()
        doPrint([res.data])
        $baseMessage(res.msg || '操作成功！', 'success')
        if (state.dispatchData.useMold) {
          getReportByPkMid()
        } else {
          getReportBill()
        }
      } catch (error) {
        console.log(error)
        load.close()
        $baseMessage('操作失败!', 'error')
      }
    } else {
      $baseMessage('请先选择报工单', 'error')
    }
  }

  const toPrint = async () => {
    if (state.currentRow) {
      const load = $baseLoading()
      try {
        const res = await webPrintBarcodeApi({
          reportCode: state.currentRow.reportCode,
        })
        load.close()
        doPrint(res.data)
      } catch (error) {
        load.close()
        $baseMessage('操作失败!', 'error')
      }
    } else {
      $baseMessage('请先选择报工单', 'error')
    }
  }

  const doPrint = (barcodeInfoList) => {
    hiPrint(state.printTemplateCode, barcodeInfoList)
  }

  const toShowReport = () => {
    reportVisible.value = true
  }
  const changeCallback = (dataForm, reportIndex) => {
    state.reportDataList[reportIndex]['mesReport']['qualifiedQty'] =
      dataForm.qualifiedQty || 0
    state.reportDataList[reportIndex]['mesReport']['declareQty'] =
      dataForm.declareQty || 0
    state.reportDataList[reportIndex]['mesReport']['scrapQty'] =
      dataForm.scrapQty || 0
    state.reportDataList[reportIndex]['mesReport']['remark'] =
      dataForm.remark || ''
  }
  const toChangeAlone = (reportItem, reportIndex) => {
    changeQtyDialogRef.value.handleOpen(reportItem, reportIndex)
  }
  const toChangeQty = (field) => {
    if (!state.dispatchData.useMold) {
      return
    }
    if (!state.reportDataList || state.reportDataList.length === 0) {
      const mesReportTemp = {
        qualifiedQty: 0,
        scrapQty: 0,
        declareQty: 0,
        remark: '',
      }
      mesReportTemp[field] = state.form[field] || ''
      state.reportDataList = JSON.parse(
        JSON.stringify(state.dispatchData?.dispatches || [])
      ).map((dItem) => {
        return {
          ...dItem,
          mesReport: mesReportTemp,
        }
      })
    } else {
      state.reportDataList.forEach((rItem) => {
        rItem['mesReport'][field] = state.form[field] || ''
      })
    }
  }

  const queryPicking = async () => {
    const { data } = await getMesPickingApi({
      pkDispatch: state.dispatchData.pkDispatch,
    })
    state.pickingForList = data
  }

  const queryMaterial = async () => {
    const { data } = await getMaterialHApi({
      pkDispatch: state.dispatchData.pkDispatch,
    })
    state.materialList = data
  }
  const queryPickingForMold = async () => {
    const { data } = await getPickingForMoldApi({
      pkMid: state.dispatchData.pkDispatchMid,
    })
    state.pickingForList = data
  }
  const queryMaterialHMold = async () => {
    const { data } = await getMaterialHMoldApi({
      pkDispatchMid: state.dispatchData.pkDispatchMid,
    })
    state.materialList = data
  }
  const toPackageReport = () => {
    state.reportDataList = JSON.parse(
      JSON.stringify(state.dispatchData?.dispatches || [])
    ).map((dItem) => {
      return {
        ...dItem,
        mesReport: {
          qualifiedQty: state.pickBox.rate,
          scrapQty: 0,
          declareQty: 0,
        },
      }
    })
  }

  // 123
  const doMesReport = async () => {
    const equTemp = JSON.parse(JSON.stringify(state.equipData))
    const pickingForListTemp = JSON.parse(JSON.stringify(state.pickingForList))
    const materialListTemp = JSON.parse(JSON.stringify(state.materialList))
    equTemp['mesPickings'] = pickingForListTemp
    equTemp['mesMaterialHs'] = materialListTemp
    equTemp['mesReport'] = {
      qualifiedQty: state.form.qualifiedQty || 0,
      scrapQty: state.form.scrapQty || 0,
      declareQty: state.form.declareQty || 0,
      fangongQty: state.form.fangongQty || 0,
      remark: state.form.remark || '',
    }
    equTemp['mesDispatch'] = state.dispatchData
    equTemp['sns'] = []
    equTemp['mesDispatchSeqs'] = []
    const load = $baseLoading()
    try {
      const res = await mesReportAloneApi(equTemp)
      load.close()
      reportVisible.value = false
      $baseMessage(res.msg || '报工成功！', 'success')
      getReportBill()
    } catch (error) {
      load.close()
      $baseMessage('报工有误！', 'error')
    }
  }

  const doMoldReport = async () => {
    const equTemp = JSON.parse(JSON.stringify(state.equipData))
    const pickingForListTemp = JSON.parse(JSON.stringify(state.pickingForList))
    const materialListTemp = JSON.parse(JSON.stringify(state.materialList))
    equTemp['mesPickings'] = pickingForListTemp
    equTemp['mesMaterialHs'] = materialListTemp
    const dispatchDataTemp = JSON.parse(JSON.stringify(state.dispatchData))
    dispatchDataTemp['dispatches'] = state.reportDataList
    equTemp['mesDispatchSeq'] = dispatchDataTemp
    equTemp['sns'] = []
    equTemp['mesDispatchSeqs'] = []

    const load = $baseLoading()
    try {
      const res = await mesReportMoldApi(equTemp)
      load.close()
      reportVisible.value = false
      $baseMessage(res.msg || '报工成功！', 'success')
      getReportByPkMid()
    } catch (error) {
      load.close()
      $baseMessage('报工有误！', 'error')
    }
  }
  const queryPickingBox = async () => {
    const dispatcheItem = state.dispatchData?.dispatches?.[0]
    if (dispatcheItem) {
      const { data } = await queryPickingBoxApi({ pkInv: dispatcheItem.pkInv })
      state.pickBox = (data && data.length > 0 && data?.[0]) || null
      console.log('queryPickingBox', state.pickBox)
    }
  }
  const getReportByPkMid = async () => {
    const { data } = await getReportByPkMidApi({
      pkCorp,
      pkDispatchMid: state.dispatchData.pkDispatchMid,
    })
    state.reportList = data
  }

  const getReportBill = async () => {
    const { data } = await getReportBillApi({
      pkCorp,
      pkDispatch: state.dispatchData.pkDispatch,
    })
    state.reportList = data
  }

  const initRecord = () => {
    queryPickingBox()
    if (state.dispatchData.useMold) {
      queryPickingForMold()
      queryMaterialHMold()
      getReportByPkMid()
    } else {
      queryPicking()
      queryMaterial()
      getReportBill()
    }
  }

  const toShow = (dispatchData, equipData) => {
    visible.value = true
    state.dispatchData = dispatchData
    state.equipData = equipData
    initRecord()
  }
  const toHide = () => {
    visible.value = false
    state.dispatchData = null
  }

  const queryTempList = async () => {
    const param = {
      pageNum: 1,
      pageSize: 1000,
      printTemplateCode: '',
      printTemplateName: '',
      isUse: 0,
      pkCorp,
    }
    const { data = {} } = await queryTemp(param)
    state.mbList = (data?.list || []).map((item) => {
      item['printTemplateCode'] = item.printTemplateCode?.trim()
      return item
    })
  }

  const inspect = () => inspectDialogRef.value.openDialog(state.currentRow)

  const insepectCallback = () => initRecord()

  onMounted(() => {
    queryTempList()
  })
  defineExpose({
    toShow,
    toHide,
  })
</script>
<style lang="scss" scoped>
  .report-module {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 999;
    width: 320px;
    height: calc(100vh - 100px);
    padding: 12px;
    background-color: #f0f1f2;
    border-radius: 5px;

    .report-mold-root {
      position: absolute;
      top: 160px;
      right: 0;
      bottom: 45px;
      left: 0;
      overflow-y: scroll;
    }
    .report-mold-item {
      padding: 6px 6px 3px 6px;
      margin: 3px;
      cursor: pointer;
      background-color: #e0e0e0;
      border-radius: 5px;
      .report-invname {
        font-size: 14px;
        font-weight: bold;
        color: #333;
      }
      .report-invcode {
        font-size: 12px;
        color: #999;
      }
      .report-data-root {
        display: flex;
        margin-top: 6px;
        .report-label {
          font-size: 12px;
          color: #666;
        }
        .report-val {
          font-size: 14px;
          font-weight: bold;
        }
      }
    }

    :deep(.el-input__wrapper) {
      background: none;
      border-bottom: 1px solid #e0e0e0;
      box-shadow: none;
    }
    :deep(.el-input-number .el-input__inner) {
      text-align: left;
    }
    :deep(.el-form-item) {
      margin-bottom: 3px;
    }
    .btn-root {
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      display: flex;
      line-height: 42px;
      text-align: center;
    }
    .btn-report {
      font-size: 18px;
      font-weight: 700;
      color: #ffffff;
      cursor: pointer;
      background: linear-gradient(180deg, #4793ff, #0064e4);

      // #79bbff #409eff
    }
    .btn-report:hover {
      font-size: 18px;
      font-weight: 700;
      color: #ffffff;
      cursor: pointer;
      background: linear-gradient(180deg, #79bbff, #409eff);
    }

    // #e6a23c #eebe77
    // #f3d19e #f8e3c5

    .btn-package {
      font-size: 18px;
      font-weight: 700;
      color: #333;
      cursor: pointer;
      background: linear-gradient(180deg, #e6a23c, #eebe77);
    }
    .btn-package:hover {
      font-size: 18px;
      font-weight: 700;
      color: #333;
      cursor: pointer;
      background: linear-gradient(180deg, #f3d19e, #f8e3c5);
    }

    .btn-disable {
      font-size: 18px;
      font-weight: 700;
      color: #999;
      cursor: not-allowed;
      background: #fde2e2;
    }
  }
  .scrollable::-webkit-scrollbar {
    display: none;
  }
</style>
